package com.yungu.swift.api.utils;


import com.yungu.swift.utils.StringUtils;

import java.util.Random;

/**
 * 将关键数据进行加密
 */

public class RandomUtil {

    private static final String MESSAGE_KEY = "AESCipher1234567";
    private static final String WRAP_KEY = "YYcx1289qazRan@!";

    /**
     * 9sQqwKeE+WOdSChiA+A/lKYcmCjQpZBT0By7YJObG4IFXMT/MmzxswtGfDoQqjxg&codeType=1&sendType=1&noncestr=
     * 加密
     * ASE(8（随机8位）+ 数据(ASE) + 8（随机8位）)
     *
     * @param value
     * @return
     */
    public static String randomEncrypt(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        return AESCipher.encryptAES(randomString(8) + AESCipher.encryptAES(value, RandomUtil.MESSAGE_KEY) + randomString(8), WRAP_KEY).replaceAll("\\+", "-").replaceAll("/", "_");
    }

    /**
     * 解密
     *
     * @param value
     * @return
     */
    public static String randomDecrypt(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        if (value.length() == 4 || value.length() == 11 || value.length() == 18) {
            return value;
        }
        value = AESCipher.decryptAES(value.replaceAll("_", "/").replaceAll("-", "\\+"), WRAP_KEY);
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        return AESCipher.decryptAES(value.substring(8, value.length() - 8), RandomUtil.MESSAGE_KEY);
    }

    /**
     * 产生一个随机的字符串
     */
    private static String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            //62顺位
            sb.append(str.charAt(random.nextInt(62)));
        }
        return sb.toString();
    }


}
